import 'package:flutter/material.dart';

import 'package:sharing/model/own_book_list.dart';
import 'package:sharing/net/net_util.dart';
import 'package:sharing/net/ris_read_apis.dart';
import 'package:dio/dio.dart';
import 'package:sharing/utils/whole_apis.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:sharing/ui/widget/book_info.dart';
import 'package:sharing/model/book.dart';

class BookListDetail extends StatefulWidget {
  final OwnBookList ownBookList;

  BookListDetail({Key key, @required this.ownBookList}) : super(key: key);

  _BookListDetailState createState() => _BookListDetailState();
}

class _BookListDetailState extends State<BookListDetail> {
  List<Book> _bookListItems = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _fetchBookListDetail();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.ownBookList.name),
          actions: <Widget>[
            IconButton(
              icon: Text(widget.ownBookList.publish ? "公开" : "个人"),
              onPressed: () {},
            ),
          ],
        ),
        body: ListView.builder(
          itemCount: _bookListItems.length + 1,
          itemBuilder: (BuildContext context, int index) {
            if (index < _bookListItems.length) {
              return _BookListDetailItem(
                book: _bookListItems[index],
              );
            } else {
              return Container(
                height: 48,
                width: double.infinity,
                child: Center(
                  child: Text(
                    "(●'◡'●)没有了",
                    style: TextStyle(
                      fontSize: 16.0,
                      color: Colors.black26,
                    ),
                  ),
                ),
              );
            }
          },
        ),
      ),
    );
  }

  void _fetchBookListDetail() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String authorization = await prefs.getString("authorization");

    NetUtil.originGet(
        WholeApis.hostName +
            RisReadApis.bookList +
            "?bkId=" +
            widget.ownBookList.id.toString(),
        Options(
          headers: {
            "authorization": authorization,
          },
        ),
        // callback
        (Response response) {
      if (response.statusCode != 200) {
        print("error ");
        return;
      }
      print("data is ${response.data}");

      // 返回的数据为空...退出
      if (response.data == null) {
        return;
      }
      // 反序列化json 字符串
      var data = json.encode(response.data);
      var mapData = json.decode(data);

      print("data => $data");

      var code = mapData['code'];

      if (code == WholeApis.paramsErr) {
        // todo
        print("参数错误..... ");
        return;
      } else if (code == WholeApis.loginOutTime) {
        // todo
        print("登录超时");
        return;
      } else if (code == WholeApis.permissionDefined) {
        // todo
        print("禁止访问");
        return;
      } else if (code == WholeApis.missErr) {
        // todo
        print("error ");
        return;
      }
      mapData = mapData['message'];

      if (mapData == null) {
        print("该书单没有任何书籍");
        return;
      }
      _bookListItems.clear();
      _bookListItems = Book.fromJson(mapData);
//      mapData.forEach((o) {
//        Book item = Book();
//        print("data $o");
//        item.id = o["id"];
//        item.name = o["name"];
//        item.copyRight = o["copyright"];
//        item.link = o["link"];
//        item.author = o["author"];
//        item.cover = o["cover"];
//        item.saveName = o["save_name"];
//        //  ownBookList.publishTime = new DateTime(o["publish_time"]);
//
//        _bookListItems.add(item);
//      });
      setState(() {});
    });
  }
}

class _BookListDetailItem extends StatelessWidget {
  Book book;

  _BookListDetailItem({@required this.book});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8.0),
        child: Container(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              Container(
                child: SizedBox(
                  height: 75.0,
                  width: 100,
                  child: book.cover != null
                      ? Image.network(
                          WholeApis.hostName+"/"+book.cover,
                          fit: BoxFit.cover,
                        )
                      : Text("封面已经被关进小黑屋"),
                ),
              ),
              Expanded(
                child: Container(
                  margin: const EdgeInsets.symmetric(horizontal: 8.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        margin: const EdgeInsets.symmetric(horizontal: 4.0),
                        child: Text(book.name),
                      ),
                      Container(
                        margin: const EdgeInsets.symmetric(horizontal: 4.0),
                        child: Text("zuo " +( book.author==null?"":book.author)),
                      ),
                      Container(
                        margin: const EdgeInsets.symmetric(horizontal: 4.0),
                        child: Text("©" + (book.copyRight==null?"":book.copyRight)),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      onTap: () {
        print("$book");
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (context) {
            return BookInfo(
              book: book,
            );
          }),
        );
      },
    );
  }
}
